package com.logic.landseaserver.common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.exception.LandseaException;

/**
 * Created by Junny on 2017/6/30.
 */
public abstract class FileTool
{
    private static final Logger LOG = LoggerFactory.getLogger(FileTool.class);
    
    public static void reName(String filePath, String fileName)
    {
        File f = new File(filePath);
        String c = f.getParent();
        File mm = new File(c + "/" + fileName);
        try
        {
            if (f.exists())
            {
                f.renameTo(mm);
            }
            
        }
        catch (Exception e)
        {
            LOG.error("reName error.", e);
        }
        
    }
    
    /**
     * 从网络Url中下载文件 Aaron.Wang 2017///07/07
     * 
     * @param urlStr 网络文件地址
     * @param fileName 保存到本地的文件名
     * @param savePath 保存的绝对路径
     * @throws IOException
     */
    public static void downLoadFromUrl(String urlStr, String fileName, String savePath)
        throws IOException
    {
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try
        {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            // 设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            
            // 得到输入流
            inputStream = conn.getInputStream();
            // 获取自己数组
            byte[] getData = readInputStream(inputStream);
            
            // 文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists())
            {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            fos = new FileOutputStream(file);
            fos.write(getData);
        }
        catch (Exception e)
        {
            LOG.error("downloadFile|down load file from " + urlStr + " failed,local save path is " + savePath
                + ".fileName=" + fileName, e);
        }
        finally
        {
            try
            {
                if (fos != null)
                {
                    fos.close();
                }
                if (inputStream != null)
                {
                    inputStream.close();
                }
            }
            catch (Exception e2)
            {
                LOG.error("downloadFile|down load file from " + urlStr + " failed,local path is " + savePath
                    + ".fileName=" + fileName, e2);
            }
        }
    }
    
    /**
     * 从输入流中获取字节数组
     * 
     * @param inputStream
     * @return 字节流数组
     * @throws LandseaException
     */
    public static byte[] readInputStream(InputStream inputStream)
        throws LandseaException
    {
        ByteArrayOutputStream bos = null;
        try
        {
            byte[] buffer = new byte[1024];
            int len = 0;
            bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1)
            {
                bos.write(buffer, 0, len);
            }
            bos.close();
            return bos.toByteArray();
        }
        catch (Exception e)
        {
            LOG.error("readInputStream error.", e);
            throw LandseaException.createException(LandseaErrorMessageEnum.COMMON_READ_STREAM_ERROR, e);
        }
    }
    
    /**
     * 
     * [简要描述]：</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2018-01-11)</br>
     *
     * @param path 文件路径例如：/opt/a/b
     * @param fileName 文件名 例如：Articale.html
     * @param content 内容
     *
     */
    public static void createFileWithContent(String path, String fileName, String content)
    {
        if (StringUtils.isEmpty(path) || StringUtils.isEmpty(fileName))
        {
            LOG.error("createFileWithContent error.文件路径为空或文件名为空.");
            return;
        }
        
        // 字节输出流
        FileOutputStream fos = null;
        try
        {
            // 文件保存位置
            File saveDir = new File(path);
            if (!saveDir.exists())
            {
                saveDir.mkdir();
            }
            
            String fileFullName = saveDir + File.separator + fileName;
            LOG.info("createFileWithContent|生成文件" + fileFullName);
            if (StringUtils.isEmpty(content))
            {
                File file = new File(fileFullName);
                fos = new FileOutputStream(file);
                fos.write(new byte[0]);
            }
            else
            {
                File dest = new File(fileFullName);
                fos = new FileOutputStream(dest);
                fos.write(content.getBytes());
            }
            
            fos.close();
        }
        catch (Exception e)
        {
            LOG.error("createFileWithContent error.", e);
        }
        finally 
        {
            if (null != fos)
            {
                try
                {
                    fos.close();
                }
                catch (IOException e)
                {
                    LOG.error("createFileWithContent error close io error.", e);
                }
            }
        }
    }
}